/*
 * UARTTest.c
 *
 * Created: 2011-11-04 08:51:02
 *  Author: SZCZUR
 */ 

#define F_CPU 8000000

#include <avr/io.h>


void USART_Init( unsigned int ubrr)
{
	/* Set baud rate */
	UBRRH = (unsigned char)(ubrr>>8);
	UBRRL = (unsigned char)ubrr;
	/* Enable receiver and transmitter */
	UCSRB = (1<<RXEN)|(1<<TXEN);
	/* Set frame format: 8data, 2stop bit */
	UCSRC = (1<<URSEL)|(1<<USBS)|(3<<UCSZ0);
}

void USART_Transmit8( unsigned char data )
{
	/* Wait for empty transmit buffer */
	while ( !( UCSRA & (1<<UDRE)) )
	;
	/* Put data into buffer, sends the data */
	UDR = data;
}

void USART_Transmit9( unsigned int data )
{
	/* Wait for empty transmit buffer */
	while ( !( UCSRA & (1<<UDRE)) )
	;
	/* Copy ninth bit to TXB8 */
	UCSRB &= ~(1<<TXB8);
	if ( data & 0x0100 )
	UCSRB |= (1<<TXB8);
	/* Put data into buffer, sends the data */
	UDR = data;
}

unsigned char USART_Receive8( void )
{
	/* Wait for data to be received */
	while ( !(UCSRA & (1<<RXC)) )
	;
	/* Get and return received data from buffer */
	return UDR;
}


unsigned int USART_Receive9( void )
{
	unsigned char status, resh, resl;
	/* Wait for data to be received */
	while ( !(UCSRA & (1<<RXC)) )
	;
	/* Get status and ninth bit, then data */
	/* from buffer */
	status = UCSRA;
	resh = UCSRB;
	resl = UDR;
	/* If error, return -1 */
	if ( status & (1<<FE)|(1<<DOR)|(1<<PE) )
	return -1;
	/* Filter the ninth bit, then return */
	resh = (resh >> 1) & 0x01;
	return ((resh << 8) | resl);
}


void USART_str(const char* str) {
	while (*str != 0) {
		USART_Transmit8(*str);
		str++;
	}
}

int main(void)
{
	// 51 = 9600
	// 12 = 38.4
	USART_Init(12);
	
	USART_str("Begin");
	
    while(1)
    {
        unsigned char d = USART_Receive8();
		USART_Transmit8(d);
    }
}